package com.ctu.autodial;

import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import com.ctu.app.utils.ConfigureLog4J;
//import com.ctu.app.utils.LogUtil;

import android.app.Application;
import android.content.Intent;
import android.util.Log;

/**
 * 在应用启动的时候，在Application中注册异常处理机制
 * 
 * 在应用重启的时候，启动服务
 * 
 * @author wxm
 * 
 */
public class CrashApplication extends Application {
	private static final String TAG = "CrashApplication";
	private static final String EXCEPTION_FILE_NAME = "AutoDialRunException";
	static CrashApplication instance;
	private static Logger runLogger;

	/**
	 * context
	 * 
	 * @return
	 */
	public static CrashApplication getInstance() {

		return instance;
	}

	public static Logger getLoggerInstance() {
		return runLogger;

	}

	@Override
	public void onCreate() {
		super.onCreate();

		Log.d(TAG, "onCreate");
		instance = this;
		runLogger = ConfigureLog4J.configure();

		// LogUtil.createSDCardDir("autodial");// 创建录音保存文件
		// LogUtil.createSDCardDir("log/AutoDialRunLog");//
		// sdcard/log/AutoDialRunLog
		// LogUtil.saveLog2File("AutoDial启动了...");
		runLogger.info("AutoDial启动了...");

		// 获取异常处理类实例
		CrashHandler mCrashHandler = CrashHandler.getInstance();
		mCrashHandler.init(this);// 异常捕获

		// rebootTimer();// 定时重启
	}

	private void rebootTimer() {
		Timer timer = new Timer();
		// timer.schedule(new RebootTimerTask(), 10 * 1000, 10 * 1000);
		timer.schedule(new RebootTimerTask(), 60 * 60 * 1000, 60 * 60 * 1000);
		// 每隔1小时重启设备一次
	}

	/**
	 * 应用开启1小时要重启一次
	 * 
	 * @author wxm
	 * 
	 */
	class RebootTimerTask extends TimerTask {
		@Override
		public void run() {
			// Looper.prepare();
			// Toast.makeText(MainActivity.this, "定时器", 1).show();
			runLogger.info("垃圾回收");
			// LogUtil.saveLog2File("垃圾回收");
			System.gc();
			// LogUtil.saveLog2File("重启设备", LOG_FILE_NAME);
			// CommonUtils.reboot();
			// Looper.loop();

		}
	}

	/**
	 * 内存不够，需要gc
	 */
	@Override
	public void onLowMemory() {
		super.onLowMemory();
		runLogger.info("内存不足");
		// LogUtil.saveLog2File("内存不足");
		System.gc();
	}
}
